package forkjoin;

import java.util.concurrent.RecursiveTask;

public class ForkJoinBean extends RecursiveTask<Long> {

    private Long start;
    private Long end;
    private Long temp=10000L;//临界值

    public ForkJoinBean(Long start, Long end) {
        this.start = start;
        this.end = end;
    }
    @Override
    protected Long compute() {
        Long sum = 0L;
        if ((end-start)<temp){
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
        }else {
            //forkjoin
            Long middle = (start+end)/2;//中间值
            ForkJoinBean fork1 = new ForkJoinBean(start, middle);
            fork1.fork();//把任务1压入队列
            ForkJoinBean fork2 = new ForkJoinBean(middle+1, end);
            fork2.fork();//把任务2压入队列
            sum = fork1.join() + fork2.join();
        }
        return sum;
    }
}
